<template>
  <view class="ikz-bid">
    <!-- ad -->
    <!-- list -->
    <view class="ikz-sticky-box" id="ikz-sticky-box">
      <view
        class="ikz-sticky-title"
        v-for="(item, index) in type_list.list"
        :key="index"
      >
        <text
          class="ikz-textcenter"
          :style="
            current == index
              ? 'font-weight: 800;color: #FDAF66;border-bottom:6rpx solid #FDAF66;'
              : ''
          "
          @click="change"
          :data-index="index"
          :data-id="item.id"
        >
          {{ item.server_name }}
        </text>
      </view>
    </view>
    <!-- 内容 -->
    <view class="ikz-content" v-if="goodsList.length">
      <view
        class="goods-item"
        v-for="(goods, index) in goodsList"
        :key="index"
        @click="goToDetail(goods.id)"
      >
        <image :src="goods.image" class="goods-image" mode="aspectFill"></image>
        <view class="goods-info">
          <view class="goods-name">{{ goods.name }}</view>
          <view class="goods-price">价格: {{ goods.price }} 元</view>
          <view class="goods-specification">规格: {{ goods.unit }}</view>
          <view class="goods-category">
            分类: {{ getCategoryName(goods.category_id) }}
          </view>
        </view>
        <view class="button-group">
          <!-- 添加编辑按钮 -->
          <button @click="editProduct(goods.id); $event.stopPropagation()" type="primary" size="mini">
            编辑
          </button>
          <!-- 添加删除按钮 -->
          <button
            @click="
              deleteProduct(goods.id);
              $event.stopPropagation();
            "
            type="warn"
            size="mini"
          >
            删除
          </button>
        </view>
      </view>
    </view>
    <!-- 空 -->
    <view class="ikz-more" v-else>
      <image class="ikz-empty" src="/static/empty.png"></image>
    </view>
    <!-- 添加商品入口 -->
    <view class="add-product" @click="getAddProduct">
      <button type="primary">新增商品</button>
    </view>
  </view>
</template>
<script>
var app = getApp();
import ikz from "@/pages/Common/tools.js";
export default {
  data() {
    return {
      current: 0,
      type_list: {
        list: [
          {
            id: "",
            server_name: "全部",
          },
          {
            id: "normal",
            server_name: "已上架",
          },
          {
            id: "hidden",
            server_name: "已下架",
          },
          {
            id: "examine",
            server_name: "审核中",
          },
          {
            id: "2",
            server_name: "驳回",
          },
        ],
      },
      goodsList: [],
      classificationList: [],
      isMounted: false // 新增标志位
    };
  },
  onShow() {
    this.getCategoryList();
  },
  mounted() {
    this.isMounted = true; // 视图渲染完成后设置标志位为 true
  },
  methods: {
    // 获取商品列表
    getProductList: function () {
      // 显示加载中提示
      uni.showLoading({
        mask: true,
      });
      console.log(app.globalData, "app.globalDataapp.globalData");
      var path = "/xyb/supermarket/goods/list";
      var data = {
        page: 1,
        page_size: 100,
        token: uni.getStorageSync("local_user_session")
      };
      // 如果当前选中的是驳回分类，则添加 examine_status 筛选条件
      if (this.type_list.list[this.current].id === '2') {
        data.examine_status = 2;
      } else {
        data.status = this.type_list.list[this.current].id
      }
      ikz.get(path, data, (res) => {
        const newGoodsList = res.data.data.data.map((item) => {
          return {
            ...item,
            image: app.globalData.adminImgPath + "/" + item.image,
          };
        });
        this.goodsList = newGoodsList;
        // 请求结束，关闭加载中提示
        uni.hideLoading();
      });
    },
    // 跳转到商品详情页
    goToDetail: function (goodsId) {
      uni.navigateTo({
        url: `/pages/Component/merchant/goods/details/index?id=${goodsId}`,
      });
    },
    // 跳转到商品编辑页
    editProduct: function (goodsId) {
      uni.navigateTo({
        url: `/pages/Component/merchant/goods/addProduct/index?id=${goodsId}&action=edit`,
      });
    },
    getAddProduct: function () {
      uni.navigateTo({
        url: `/pages/Component/merchant/goods/addProduct/index?action=add`,
      });
    },
    change: function (e) {
      this.current = e.currentTarget.dataset.index;
      this.getProductList();
    },
    // 添加商品
    getAddProduct: function () {
      uni.navigateTo({
        url: "/pages/Component/merchant/goods/addProduct/index",
      });
    },
    getCategoryName(categoryId) {
      if (!this.isMounted ||!this.classificationList) return "未知分类"; // 检查视图是否渲染完成和分类列表是否存在
      const category = this.classificationList.find(
        (item) => item.id === categoryId
      );
      return category ? category.name : "未知分类";
    },
    // 删除商品方法
    deleteProduct(index) {
      uni.showModal({
        title: "提示",
        content: "确定要删除该商品吗？",
        success: (res) => {
          if (res.confirm) {
            uni.showLoading({
              mask: true,
            });
            let path = "/xyb/supermarket/goods/del";
            let data = {
              id: index,
              token: uni.getStorageSync("local_user_session"),
            };
            ikz.request(path, data, (res) => {
              if (res.statusCode == 200) {
                uni.showToast({
                  title: "删除成功",
                  icon: "none",
                });
                this.getProductList();
              }
              uni.hideLoading();
            });
          }
        },
      });
    },
    // 提交数据
    getSubmit: function () {
      this.baseFormData.unit =
        this.specifications[this.specificationsIndex].label;
      console.log(this.baseFormData, "this.baseFormData.uni");
  
      if (this.baseFormData.name == "") {
        uni.showToast({
          title: "请输入商品名称",
          icon: "none",
          duration: 2000,
        });
        return;
      }
      if (this.baseFormData.image == "") {
        uni.showToast({
          title: "请上传商品图片",
          icon: "none",
          duration: 2000,
        });
        return;
      }
  
      if (this.baseFormData.price == "") {
        uni.showToast({
          title: "请输入商品价格",
          icon: "none",
          duration: 2000,
        });
        return;
      }
      if (this.baseFormData.introduction == "") {
        uni.showToast({
          title: "请输入商品介绍",
          icon: "none",
          duration: 2000,
        });
        return;
      }
      if (this.baseFormData.category_id == "") {
        uni.showToast({
          title: "请选择商品分类",
          icon: "none",
          duration: 2000,
        });
        return;
      }
      var path = app.globalData.adminPath + "/xyb/supermarket/goods/add";
      // 复制 baseFormData 到 data
      var data = { ...this.baseFormData };
      // 如果存在 examine_status 字段，删除 status 字段
      if (data.examine_status!== undefined) {
        delete data.status;
      }
  
      const _this = this;
      uni.request({
        url: path,
        method: "POST",
        data: data,
        header: {
          token: uni.getStorageSync("local_user_session"),
        },
        success: function (res) {
          if (res.data.code == 0) {
            uni.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 2000,
            });
          } else {
            data.image = data.image.replace(/^(?:https?:\/\/)?[^\/]+/, "");
            for (const key in _this.baseFormData) {
              _this.baseFormData[key] = "";
            }
            _this.baseFormData.category_id = "1";
            _this.baseFormData.image = "/static/add.png";
            uni.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 2000,
            });
          }
        },
        fail: function (err) {
          console.error("请求失败:", err);
        },
      });
    },
    // 获取商品分类列表
    getCategoryList() {
      var path = "/xyb/supermarket/goods/category";
      var data = {
        token: uni.getStorageSync("local_user_session"),
      };
      ikz.get(path, data, (res) => {
        this.classificationList = res.data.data; // 更新分类列表
        console.log(this.classificationList,'classificationListclassificationList');
        this.getProductList();
      });
    },
  },
};
</script>

<style scoped>
.add-product {
  display: flex;
  justify-content: center;
}
.add-product button {
  position: fixed;
  bottom: 80rpx;
  background: linear-gradient(to right, #f8c66d, #fbab7e);
  width: 350rpx;
}
.ikz-sticky-box {
  /* #ifndef APP-PLUS-NVUE */
  display: flex;
  position: -webkit-sticky;
  /* #endif */
  position: sticky;
  top: var(--window-top);
  z-index: 99;
  flex-direction: row;
  margin: 0px;
  padding: 15px 0 15px 0;
  white-space: nowrap;
  overflow-x: auto;
  background: #fff;
  justify-content: space-evenly;
}
.ikz-more {
  width: 100%;
  text-align: center;
  line-height: 50rpx;
  color: #999999;
  padding-bottom: 25rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.ikz-empty {
  width: 150rpx;
  height: 150rpx;
  margin-bottom: 20rpx;
  margin-top: 150rpx;
}
.ikz-sticky-title {
  box-sizing: border-box;
  padding: 0 20rpx;
  display: inline-block;
  text-align: center;
}
.ikz-textcenter {
  padding-bottom: 10rpx;
}
.goods-item {
  display: flex;
  padding: 15rpx;
  border-bottom: 1rpx solid #eee;
  justify-content: space-between;
  align-items: center;
  background-color: #FFFFFF;
  border-radius: 8rpx;
  margin-bottom: 15rpx;
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}
.goods-image {
  width: 150rpx;
  height: 150rpx;
  margin-right: 20rpx;
  border-radius: 20rpx;
}
.goods-info {
  flex: 1;
}
.goods-name {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}
.goods-price {
  font-size: 28rpx;
  color: #f00;
  margin-bottom: 10rpx;
}
.goods-introduction {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 10rpx;
}
.goods-specification,
.goods-category {
  font-size: 24rpx;
  color: #999;
}
/* 新增按钮组样式 */
.button-group {
  display: flex;
  flex-direction: column;
  gap: 10rpx; /* 按钮之间的间距 */
}
</style>